package com.amit.servlet;

import java.io.File;


import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {
	
	
	public UploadServlet()
	{
		System.out.println("Default constructor");
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String ctxPath=request.getRealPath("/");
		File dir=new File(ctxPath,"uploaded");
		if(!dir.exists())
		{
			dir.mkdir();
		}
		
		System.out.println("Hello");
		Writer out=response.getWriter();
		boolean uploadData=ServletFileUpload.isMultipartContent(request);
	if(uploadData)
	{
		DiskFileItemFactory factory=new DiskFileItemFactory();
		factory.setSizeThreshold(1024*1024*10);
			factory.setRepository(new File("E:\\Temp"));
			System.out.println("Hello amit");
			
			ServletFileUpload upload=new ServletFileUpload(factory);
			upload.setSizeMax(1024*1024*50);
			try
			{
				System.out.println("hello123");
				List<FileItem> fileItems=upload.parseRequest(request);
				Iterator<FileItem> i=fileItems.iterator();
			while(i.hasNext())
			{
				System.out.println("hello");
			FileItem fi=i.next();
			
				if(!fi.isFormField())
				{
						String fieldName=fi.getFieldName();
						String fileName=fi.getName();
					String contentType=fi.getContentType();
					boolean isInMemory=fi.isInMemory();
					System.out.println(isInMemory);
					long sizeInBytes=fi.getSize();
					StringTokenizer tok=new StringTokenizer(fileName,"/");
						String fileToWrite=" ";
						while(tok.hasMoreElements())
						{
							fileToWrite=tok.nextToken();
						}
					File file=new File(dir, fileToWrite);
						fi.write(file);
					}
				}
			
				
			}		
			catch (Exception e) {
				e.printStackTrace();
			}
			
			System.out.println("Hello");
			out.write("<h1>File Uploaded in<br/>"+dir.getAbsolutePath());
	}
		else
		{
		out.write("No file Uploaded");
	}
	
	System.out.println("hello123455");
		
	}

}
